package cc.aiee.core.kit;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.TreeMap;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

public class KitMap {

	/**
	 * 解析字符串
	 * 
	 * @param keyVaue "key=value&key2=val2key3=value3"
	 * @param encoding "UTF-8"/CharsetUtil.UTF_8 ; value解密  
	 * @return
	 * @author YangLong <br>
	 *         2020-09-29 11:24:58
	 */
	public static Map<String, String> toMap(String keyVaue, String encoding) {
		Assert.notBlank(keyVaue);
		Map<String, String> map = new TreeMap<String, String>();
		String[] split = keyVaue.split("&");

		String key, value;
		for (String str : split) {
			String[] split2 = str.split("=");
			if (split2.length < 2) {
				continue;
			}
			key = split2[0];
			value = split2[1];
			if (StrUtil.isEmpty(value)) {
				continue;
			}
			if (StrUtil.isNotBlank(encoding)) {
				try {
					value = URLDecoder.decode(value, encoding);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			map.put(key, value);
		}
		return map;
	}

	public static Map<String, String> toMap(String keyVaue) {
		return toMap(keyVaue, null);
	}
}
